import fs from "fs";
import path from "path";
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { getPathFileList, getFileContent, formatWithPrettier, baiduTranslatekeyMap } from './utils/util.js'

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

import BaiduTranslate from "./utils/BaiduTranslate.js"; //引入百度翻译文件
import AliyunTranslate from "./utils/AliyunTranslate.js"; // 引入阿里云翻译文件


const successlist = [];
const errorlist = [];
const unchangedList = [];

const main = async (config) => {
  let translate = null;
  if (config.engine == 'baidu') {
    translate = new BaiduTranslate(config.baidu);
  } else {
    translate = new AliyunTranslate(config.aliyun);
  }

  const pathConfig = config.patchTranslation;
  try {
    const list = getPathFileList(path.resolve(pathConfig.scanPath), pathConfig.source).filter(v => v.suffix === 'json');

    /**源数据 */
    const sourceDate = await getFileContent(
      path.join(path.resolve(pathConfig.scanPath), `${pathConfig.source}.json`) // 使用 path.join 替代字符串拼接
    );
    const sourceJson = JSON.parse(sourceDate);

    // 使用for...of循环替代forEach以正确处理异步操作
    for (const item of list) {
      try {
        if (pathConfig.patch) { // 修复变量名错误，原来是 pathConfig.patch
          console.log("补全翻译模式");
          const targetContent = await getFileContent(item.path);
          const targetJson = JSON.parse(targetContent); //目标语言数据
          let needTranslate = false;

          req: for (const key of Object.keys(sourceJson)) {
            if (!Object.hasOwn(targetJson, key)) {
              if (sourceJson[key]) {
                console.log(`${item.name}.json 缺少 ${key},正在补全翻译`);
                try {
                  needTranslate = true;
                  const result = await translate(sourceJson[key], {
                    from: pathConfig.source,
                    to: config.engine == 'baidu' ? (baiduTranslatekeyMap[item.name] || item.name) : item.name,
                    scene:config.scene
                  },config.professionalMode);
                  targetJson[key] = result;
                } catch (error) {
                  console.error("翻译出错:", error);
                  needTranslate = false;
                  if (!errorlist.includes(item.name)) errorlist.push(item.name);
                  console.log(`${item.name}.json 翻译失败，语种可能不支持`);
                  break req;
                }
              }
            }
          }

          if (needTranslate) {
            console.log(`${item.name}.json 补全完成`);
            fs.writeFileSync(item.path, JSON.stringify(targetJson, null, 2));
            // 使用prettier格式化文件
            successlist.push(item.name);
            await formatWithPrettier(item.path);
          } else {
            unchangedList.push(item.name);
            console.log(`${item.name}.json 无需补全`);
          }
        } else {
          console.log("全量翻译模式");
          try {
            const result = await translate(sourceJson, {
              from: pathConfig.source,
              to: config.engine == 'baidu' ? (baiduTranslatekeyMap[item.name] || item.name) : item.name,
            });
            fs.writeFileSync(item.path, JSON.stringify(result, null, 2));
            successlist.push(item.name);
            await formatWithPrettier(item.path);
          } catch (error) {
            console.error("翻译出错:", error);
            errorlist.push(item.name);
          }
        }
      } catch (err) {
        console.error(`处理文件 ${item.path} 时出错:`, err);
      }
    }

  } catch (err) {
    console.error("主函数执行出错:", err);
  } finally {
    console.log(`处理完成，成功文件列表: ${successlist}`);
    console.log(`处理完成，失败文件列表: ${errorlist}`);
    console.log(`处理完成，无需处理文件列表: ${unchangedList}`);
  }
};

export default main;